/**
 * 1.新建一级菜单 2.新建二级菜单 3.修改菜单
 * @type Number
 */
var btntype=1;

/**
 * 用于存放当前选中菜单所有值
 */
var menuobj;

//
var siteCustomMenuRpanelTitle='菜单设置-';

var siteCustomMenuUserId=0;

Ext.onReady(function(){
	siteCustomMenuiswriteidb= Ext.get('siteCustomMenuiswriteid').getValue()==1?true:false;

	var adminSiteCustomMenunkey=new Ext.form.ComboBox({
		fieldLabel: '选择用户',
		editable:false,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectAdminUsers.do',
            fields:['nUserId','sName']
        }),
        mode:'local',
	    valueField:'nUserId',
	    displayField:'sName',
        emptyText:'全部',
        triggerAction:'all',
        selectOnFocus:true
	});
	
	var adminSiteCustomMenuSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			siteCustomMenuUserId=adminSiteCustomMenunkey.getValue();
			siteCustomMenusUrl.getStore().reload();
			siteCustomMenuTree.getRootNode().reload();
			siteCustomMenuTree.expandAll();
			siteCustomMenuRpanel.getForm().reset();
			siteCustomMenuKey.getStore().reload();
		}
	});
	
	var adminSiteCustomMenuSearch=new Ext.Panel({
		height:50,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.38,layout:'form',labelAlign:'right',items:[adminSiteCustomMenunkey]},
			{columnWidth:.2,layout:'form',labelAlign:'right',items:[adminSiteCustomMenuSearchBtn]}
		]
	});
	
    var siteCustomMenuName=new Ext.form.TextField({
		labelAlign:'right',
		width:167,
		fieldLabel: '菜单名称'
	});
	
	var siteCustomMenuSelectNpid=new Ext.form.ComboBox({
		fieldLabel:'选择一级菜单',
		labelAlign:'right',
		editable:false,
		hidden:true,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text']
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        selectOnFocus:true
	});
	
	var siteCustomMenuType=new Ext.form.ComboBox({
		fieldLabel:'功能',
		labelAlign:'right',
		editable:false,
        store: new Ext.data.ArrayStore({
            fields: ['value', 'text'],
            data:[
			        [1, '点击事件'],
			        [2, '链接']
		        ]
        }),
	    valueField:'value',
	    displayField:'text',
        mode:'local',
        typeAhead: true,
        triggerAction: 'all',
        value:1,
        selectOnFocus:true,
        listeners:{
        	select:function(combo, record,index)  {
        		menuTypeselect(index+1);
        	}
	    }
	});
	
function  menuTypeselect(index){
	switch(index){
		case 1:
			siteCustomMenuKey.show();
			siteCustomMenusUrl.hide();
			break;
		case 2:
			siteCustomMenuKey.hide();
			siteCustomMenusUrl.show();
			break;
		case 3:
			siteCustomMenuKey.hide();
			siteCustomMenusUrl.hide();
			break;
	}
}
	
	var siteCustomMenuKey=new Ext.form.ComboBox({
		fieldLabel: 'key值',
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectAdminUserKeys.do',
            fields:['nKey','nKey'],
            listeners:{
	    		beforeload:function(store,records,options){
	    			store.baseParams = {
						userid:siteCustomMenuUserId
	    			};
	    		}
            }
        }),
        hidden:false,
        editable:false,
        mode:'local',
	    valueField:'nKey',
	    displayField:'nKey',
        emptyText:'0',
        triggerAction:'all',
        selectOnFocus:true
	});
	
	var siteCustomMenusUrl=new Ext.form.ComboBox({
		fieldLabel: '点击跳转链接',
		editable:false,
		hidden:true,
        store: new Ext.data.JsonStore({
        	autoLoad:true,
            url:'selectAdminUserUrl.do',
            fields:['sName','nWxUserUrlId'],
            listeners:{
	    		beforeload:function(store,records,options){
	    			store.baseParams = {
						userid:siteCustomMenuUserId
	    			};
	    		}
            }
        }),
        mode:'local',
	    valueField:'nWxUserUrlId',
	    displayField:'sName',
        emptyText:'全部',
        triggerAction:'all',
        selectOnFocus:true
	});
	
	var siteCustomMenuOrder=new Ext.form.NumberField({
		labelAlign:'right',
		width:167,
		value:0,
		fieldLabel: '排序号'
	});
	var siteCustomMenuRemark=new Ext.form.TextArea({
		labelAlign:'right',
		width:167,
		height:100,
		fieldLabel: '备注'
	});
	
    var siteCustomMenuExplain=new Ext.form.Label({
		labelAlign:'right',
		text:'说明：目前自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替。请注意，创建自定义菜单后，由于微信客户端缓存，需要24小时微信客户端才会展现出来。建议测试时可以尝试取消关注公众账号后再次关注，则可以看到创建后的效果。'
	});
	
	var siteCustomMenuSaveBtn =new Ext.Button({
		text:'保存',
		icon: "../../extjs/resources/images/default/tree/drop-yes.gif", 
        cls: "x-btn-text-icon" ,
		handler:function(){
			if(btntype==1){
				
				var rootnode = siteCustomMenuTree.getRootNode();
				if(rootnode.childNodes.length>=3){
					Ext.Msg.alert("添加失败！","自定义菜单最多包括3个一级菜单！"); 
				}else{
					siteCustomMenuSave(0);
				}
				
			}else if(btntype==2){
				
				var npidnode = siteCustomMenuTree.getNodeById(siteCustomMenuSelectNpid.getValue());
				if(npidnode.childNodes.length>=5){
					Ext.Msg.alert("添加失败！","自定义菜单最多包括5个二级菜单！"); 
				}else{
					siteCustomMenuSave(siteCustomMenuSelectNpid.getValue());
				}
				
			}else if(btntype==3){
				siteCustomMenuUpdate();
			}
		}
	});
    
    var siteCustomMenuRpanel=new Ext.FormPanel({
    	frame:true,
    	region: 'center',
        title: siteCustomMenuRpanelTitle,
        autoScroll: true,
        collapsible: true,
        border:false,
        margins: '0 0 0 10',
        labelAlign:'right',
        items:[siteCustomMenuSelectNpid,
        	siteCustomMenuName,siteCustomMenuOrder,siteCustomMenuType,
        	siteCustomMenuKey,siteCustomMenusUrl,siteCustomMenuRemark,
        	siteCustomMenuExplain],
        buttons:[siteCustomMenuSaveBtn]
//        html: detailsText
    });
    
    var siteTextAddBtn =new Ext.Button({
		text:'新建一级菜单',
		icon: "../../extjs/resources/images/default/tree/drop-add.gif", 
        cls: "x-btn-text-icon" ,
//        style:'background: url(../../extjs/resources/images/default/tree/drop-add.gif) left top no-repeat;   ',
		handler:function(){
			btntype=1;
			siteCustomMenuRpanel.setTitle(siteCustomMenuRpanelTitle+siteTextAddBtn.getText());
			siteCustomMenuRpanel.getForm().reset();
			siteCustomMenuSelectNpid.hide();
			menuTypeselect(3);
			
			if(siteCustomMenuTree.getSelectionModel().getSelectedNode()){
				siteCustomMenuTree.getSelectionModel().getSelectedNode().unselect();
			}
		}
	});
	
	var siteTextAdd2Btn =new Ext.Button({
		text:'新建二级菜单',
		icon: "../../extjs/resources/images/default/tree/drop-add.gif", 
        cls: "x-btn-text-icon" ,
		handler:function(){
			btntype=2;
			siteCustomMenuRpanel.setTitle(siteCustomMenuRpanelTitle+siteTextAdd2Btn.getText());
			siteCustomMenuRpanel.getForm().reset();
			siteCustomMenuSelectNpid.show();
			
			var rootnode = siteCustomMenuTree.getRootNode();
			siteCustomMenuSelectNpid.getStore().removeAll();
			for (var index = 0; index < rootnode.childNodes.length; index++) {
				var record = new Object();
        		record.value=rootnode.childNodes[index].id;
        		record.text = rootnode.childNodes[index].text;   
   		 		var records = new Ext.data.Record(record);
   		 		siteCustomMenuSelectNpid.getStore().add(records);
			}
		}
	});
	
	var siteTextAddDelBtn =new Ext.Button({
		text:'删除菜单',
		icon: "../../extjs/resources/images/default/tree/drop-no.gif", 
        cls: "x-btn-text-icon" ,
		handler:function(){

			if(siteCustomMenuTree.getSelectionModel().getSelectedNode()){
				siteCustomMenuDelete();
			}else{
				alert("请选择一个菜单");
			}
			
		}
	});
	
	var siteTextAddMobileBtn =new Ext.Button({
		text:'手机菜单同步',
		icon: "../../extjs/resources/images/default/tree/drop-yes.gif", 
        cls: "x-btn-text-icon" ,
		handler:function(){
			siteCustomMenuAddMobile();
		}
	});
	var siteTextAddDelMobileBtn =new Ext.Button({
		text:'手机菜单删除',
		icon: "../../extjs/resources/images/default/tree/drop-no.gif", 
        cls: "x-btn-text-icon" ,
		handler:function(){
			siteCustomMenuDelMobile();
		}
	});
	
	var siteCustomMenuTreeLoader=new Ext.tree.TreeLoader({
    	dataUrl:'searchAdminCustomMenu.do',
    	baseParams:{
    		userid:siteCustomMenuUserId
    	}
    });
    
	siteCustomMenuTreeLoader.on("beforeload", function(thiz, options) { 
		thiz.baseParams["userid"] = siteCustomMenuUserId;
	});
	
    var siteCustomMenuTree=new Ext.tree.TreePanel({
//    	 xtype: 'treepanel',
//        id: 'tree-panel',
    	autoLoad:false,
        region: 'west',
        autoScroll: true,
        header:true,
        rootVisible:false,
        border:false,
        title:'菜单列表',
        width:500,
        root: {
	        	nodeType: 'async',
	            text: 'Ext JS',
	            draggable: true,
	            id: 'src'
	        },
	    loader:siteCustomMenuTreeLoader,        
        listeners: {
            'render': function(tp){
                tp.getSelectionModel().on('selectionchange', function(tree, node){
//                    if(node && node.leaf){
                	 if(node){
                	 	btntype=3;
                	 	menuobj=node.attributes;
                	 	siteCustomMenuSelectNpid.hide();
                	 	siteCustomMenuRpanel.setTitle(siteCustomMenuRpanelTitle+"修改菜单");
                	 	siteCustomMenuName.setValue(menuobj.text);
                	 	siteCustomMenuOrder.setValue(menuobj.NOrder);
                	 	siteCustomMenuType.setValue(menuobj.ntype);
                	 	siteCustomMenuKey.setValue(menuobj.NKey);
                	 	siteCustomMenusUrl.setValue(menuobj.NWxUserUrlId);
                	 	siteCustomMenuRemark.setValue(menuobj.SRemark);
                	 	menuTypeselect(menuobj.ntype);
                	 }
                })
            }
        },
        tbar:[siteTextAddBtn,siteTextAdd2Btn,siteTextAddDelBtn,siteTextAddMobileBtn,siteTextAddDelMobileBtn]
    });
    
function siteCustomMenuUpdate(){
	siteCustomMenuRpanel.getForm().submit({
        url: 'updateAdminCustomMenu.do',
        method:'POST',
        waitMsg: 'Uploading your data...',
        params : {
        	userid:siteCustomMenuUserId,
        	nKey:siteCustomMenuKey.getValue(),
           	nOrder:siteCustomMenuOrder.getValue(),
           	nWxCustomMenuId:menuobj.id,
           	ntype:siteCustomMenuType.getValue(),
           	sName:siteCustomMenuName.getValue(),
           	sRemark:siteCustomMenuRemark.getValue(),
           	nWxUserUrlId:siteCustomMenusUrl.getValue()
        },
        success: function(fm, o){
        	if(o.result.success=='1'){
        		Ext.MessageBox.alert('信息!', '修改成功!');
        		siteCustomMenuTree.getRootNode().reload();
        		siteCustomMenuTree.expandAll();
        	}else{
        		Ext.MessageBox.alert('Error!', '修改失败!');
        	}
        },
		failure:function(form, action) {
			Ext.Msg.alert('错误', '保存失败！');
			return ;
		}
    });
}
function siteCustomMenuDelete(){
	Ext.MessageBox.confirm('信息', '是否确认删除 菜单： '+menuobj.text+'?', function(btn){
		if(btn=='yes'){
				Ext.Ajax.request({
					url:'delAdminCustomMenu.do',
					method:'POST',
					params : {
					   ids:menuobj.id
		            }, 
					success: function (response) {
						if(response.responseText=='1'){
		                    Ext.MessageBox.alert('信息!', '删除成功!');
		                    siteCustomMenuTree.getRootNode().reload();
        					siteCustomMenuTree.expandAll();
        					
        					btntype=1;
							siteCustomMenuRpanel.setTitle(siteCustomMenuRpanelTitle+siteTextAddBtn.getText());
							siteCustomMenuRpanel.getForm().reset();
							siteCustomMenuSelectNpid.hide();
						}
						else{
							Ext.Msg.alert("Error","删除失败！"); 
						}
		          	}, 
					failure: function (response) {
		                Ext.Msg.alert("Error","错误"); 
		        	}
				});
		}
		
	});
}
function siteCustomMenuSave(nid){
	if(siteCustomMenuUserId==0){
		return ;
	}
	
	siteCustomMenuRpanel.getForm().submit({
        url: 'saveAdminCustomMenu.do',
        method:'POST',
        waitMsg: 'Uploading your data...',
        params : {
        	userid:siteCustomMenuUserId,
        	nKey:siteCustomMenuKey.getValue(),
           	nOrder:siteCustomMenuOrder.getValue(),
           	nPid:nid,
           	ntype:siteCustomMenuType.getValue(),
           	sName:siteCustomMenuName.getValue(),
           	sRemark:siteCustomMenuRemark.getValue(),
           	nWxUserUrlId:siteCustomMenusUrl.getValue()
        },
        success: function(fm, o){
        	if(o.result.success=='1'){
        		Ext.MessageBox.alert('信息!', '保存成功!');
        		siteCustomMenuTree.getRootNode().reload();
        		siteCustomMenuTree.expandAll();
        	}else{
        		Ext.MessageBox.alert('Error!', '保存失败!');
        	}
        },
		failure:function(form, action) {
			Ext.Msg.alert('错误', '保存失败！');
			return ;
		}
    });
}

function siteCustomMenuAddMobile(){
	if(siteCustomMenuUserId==0){
		return ;
	}
	
	Ext.MessageBox.confirm('信息', '是否确认菜单与微信端同步?', function(btn){
		if(btn=='yes'){
				Ext.Ajax.request({
					url:'syncAdminCustomMenu.do',
					method:'POST',
					params : {
						userid:siteCustomMenuUserId
					}, 
					success: function (response) {
						if(response.responseText=='1'){
		                    Ext.MessageBox.alert('信息!', '同步成功!');
						}
						else{
							Ext.Msg.alert("Error","同步失败！"+response.responseText); 
						}
		          	}, 
					failure: function (response) {
		                Ext.Msg.alert("Error","错误"); 
		        	}
				});
		}
		
	});
}

function siteCustomMenuDelMobile(){
	if(siteCustomMenuUserId==0){
		return ;
	}
	
	Ext.MessageBox.confirm('信息', '是否确认删除微信端自定义菜单?', function(btn){
		if(btn=='yes'){
				Ext.Ajax.request({
					url:'delAdminSyncCustomMenu.do',
					method:'POST',
					params : {
						userid:siteCustomMenuUserId
					}, 
					success: function (response) {
						if(response.responseText=='1'){
		                    Ext.MessageBox.alert('信息!', '删除成功!');
						}
						else{
							Ext.Msg.alert("Error","删除失败！"); 
						}
		          	}, 
					failure: function (response) {
		                Ext.Msg.alert("Error","错误"); 
		        	}
				});
		}
		
	});
}
    
	var siteCustomMenuMainPanel =new Ext.Viewport({
		layout:'border',
		renderTo:'siteCustomMenuDIV',
		id:'siteCustomMenuMainPanel',
		items:[siteCustomMenuTree,siteCustomMenuRpanel,adminSiteCustomMenuSearch],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("siteCustomMenuMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
	siteCustomMenuTree.expandAll();
	siteCustomMenuRpanel.setTitle(siteCustomMenuRpanelTitle+siteTextAddBtn.getText());
});